package com.bins.cloud.gateway.filter;

import com.bins.cloud.gateway.entity.IpRateEntity;
import com.bins.cloud.gateway.limiter.CustomRedisRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class CustomFilter implements WebFilter {

    @Autowired
    private CustomRedisRateLimiter customRedisRateLimiter;
 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String ip = exchange.getRequest().getRemoteAddress().getHostName();
        log.info("ip:{}", ip);
        // 在发送响应前可以添加自定义逻辑
        // 例如，可以添加一个响应头
        exchange.getResponse().getHeaders().set("Custom-Header", "value");

        IpRateEntity ipRate = new IpRateEntity();
        ipRate.setReplenishRate(1);
        ipRate.setBurstCapacity(1);

        //如果允许同行，没有超过该ip的流量限制
        if (customRedisRateLimiter.isAllowed("ip:" + ip + ":",
                ipRate.getReplenishRate(),
                ipRate.getBurstCapacity())) {
            return chain.filter(exchange);
        } else {
            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            return exchange.getResponse().setComplete();
        }

    }
}